#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct Node
{
    int data;
    struct Node *pNext;
} NODE, *PNODE;

typedef struct Stack
{
    PNODE pTop;
    PNODE pBottom;
} STACK, *pSTACK;

void init(pSTACK);       // 栈初始化
void push(pSTACK, int);  // 压栈
void traverse(pSTACK);   // 遍历栈输出
bool is_empty(pSTACK);   // 检查栈是否为空
bool pop(pSTACK, int *); // 出栈
void clear(pSTACK);      // 清空栈

int main(void)
{
    STACK S;
    int val;
    init(&S);
    push(&S, 2);
    push(&S, 3);
    push(&S, 8);
    push(&S, 6);
    push(&S, 4);
    push(&S, 0);
    traverse(&S);
    clear(&S);
    clear(&S);
    traverse(&S);

    if (pop(&S, &val))
    {
        printf("出栈成功!\n");
        printf("出栈元素为 %d\n", val);
    }
    else
    {
        printf("出栈失败, 栈为空!\n");
    }
    traverse(&S);
    return 0;
}

void init(pSTACK pS) // 栈初始化
{
    pS->pBottom = (PNODE)malloc(sizeof(NODE));
    if (NULL == pS->pBottom)
    {
        printf("动态内存分配失败!栈初始化失败!\n");
        exit(-1);
    }
    pS->pTop = pS->pBottom;
    (pS->pBottom)->pNext = NULL;
    return;
}
void push(pSTACK pS, int val) // 压栈
{
    PNODE pNew = (PNODE)malloc(sizeof(NODE));
    if (NULL == pNew)
    {
        printf("动态内存分配失败!压栈失败!\n");
        exit(-1);
    }
    pNew->data = val;
    pNew->pNext = pS->pTop;
    pS->pTop = pNew;
    return;
}
bool is_empty(pSTACK pS) // 检查栈是否为空
{
    if (pS->pTop == pS->pBottom)
        return true;
    else
        return false;
}
void traverse(pSTACK pS) // 遍历栈输出
{
    if (is_empty(pS))
    {
        printf("栈为空，遍历失败!\n");
        return;
    }
    PNODE pTemp = pS->pTop;
    while (pTemp != pS->pBottom)
    {
        printf("%d ", pTemp->data);
        pTemp = pTemp->pNext;
    }
    printf("\n遍历完毕!\n");
    return;
}
bool pop(pSTACK pS, int *pVal) // 出栈
{
    if (is_empty(pS))
        return false;
    PNODE pTemp = pS->pTop;
    pS->pTop = (pS->pTop)->pNext;
    *pVal = pTemp->data;
    free(pTemp);
    pTemp = NULL;
    return true;
}
void clear(pSTACK pS) // 清空栈
{
    while (!is_empty(pS))
    {
        PNODE pTemp = pS->pTop;
        pS->pTop = (pS->pTop)->pNext;
        free(pTemp);
    }
    printf("栈清空完毕!\n");
    return;
}